Working with Static Variables and Static Methods in Java
Course: Core Java Training
Topic: Working with Static Variables and Static Methods
Course Link: Core Java Training Course
Demo Link: Register for a Free Course Demo
Website: JustAcademy Official Website
1. Introduction to Static Variables and Static Methods
In Java, the static keyword is used to declare members that belong to a class rather than to individual objects. Static variables and static methods are important concepts in object-oriented programming because they allow developers to share data, perform common operations, and organize utility functionality efficiently.
Normally, instance variables and instance methods are associated with individual objects. Every object can have its own copy of instance variables. In contrast, a static variable is shared by all instances of a class, and a static method can be called using the class name without creating an object.
For example, if a class represents students and needs to maintain a common college name, a static variable is suitable because the college name can be shared across all student objects.
Learning Objectives
- Understand the meaning and purpose of the
static keyword.
- Learn how to declare and initialize static variables.
- Understand how static variables are shared between objects.
- Learn how to declare and invoke static methods.
- Differentiate static members from instance members.
- Understand static method restrictions and common errors.
- Apply static variables and methods in practical Java programs.
2. What Is the Static Keyword in Java?
The static keyword is a non-access modifier used with class-level members such as variables, methods, initialization blocks, and nested classes. A static member is associated with the class itself rather than with a particular instance.
Static members can generally be accessed through the class name, which makes the code easier to understand and avoids unnecessary object creation.
Syntax
class ClassName {
static dataType variableName;
static returnType methodName() {
// Method implementation
}
}
Example
class College {
static String collegeName = "ABC College";
static void displayCollege() {
System.out.println(collegeName);
}
public static void main(String[] args) {
System.out.println(College.collegeName);
College.displayCollege();
}
}
Output
ABC College
ABC College
In this example, collegeName and displayCollege() are static members. They can be accessed using the class name, College, without creating a College object.
3. Understanding Static Variables
A static variable, also known as a class variable, is declared using the static keyword inside a class but outside any method, constructor, or block. The class has one shared static variable rather than a separate instance field for every object.
Syntax of a Static Variable
class ClassName {
static int count = 0;
}
Here, count is a static variable. All instances of the class refer to the same variable.
Example: Shared College Name
class Student {
int rollNumber;
String name;
static String college = "ABC College";
Student(int rollNumber, String name) {
this.rollNumber = rollNumber;
this.name = name;
}
void display() {
System.out.println("Roll Number: " + rollNumber);
System.out.println("Name: " + name);
System.out.println("College: " + college);
}
public static void main(String[] args) {
Student s1 = new Student(101, "Rahul");
Student s2 = new Student(102, "Priya");
s1.display();
s2.display();
}
}
Output
Roll Number: 101
Name: Rahul
College: ABC College
Roll Number: 102
Name: Priya
College: ABC College
Each student has a different roll number and name, but both students share the same college variable. This avoids maintaining duplicate copies of the same class-level information.
4. Characteristics of Static Variables
- Class-level association: A static variable belongs to its declaring class.
- Shared storage: All instances of the class share the same static field.
- Single logical copy: There is one shared field per class definition and class loader.
- Default initialization: If no explicit value is provided, a static field receives its Java default value.
- Class-name access: Static variables are best accessed using the class name.
- Memory management: Static fields remain associated with the loaded class and are not duplicated for each object.
- Shared updates: Updating a mutable static variable affects what other objects observe when they access that same field.
Default Values of Static Variables
Java automatically assigns default values to fields when they are not explicitly initialized.
| Data Type |
Default Value |
Example |
| byte |
0 |
static byte value; |
| short |
0 |
static short value; |
| int |
0 |
static int count; |
| long |
0L |
static long total; |
| float |
0.0f |
static float rate; |
| double |
0.0d |
static double amount; |
| char |
'\u0000' |
static char grade; |
| boolean |
false |
static boolean active; |
| Reference types |
null |
static String name; |
These defaults apply to fields, including static fields. Local variables declared inside methods do not receive automatic default values and must be initialized before use.
5. Modifying and Accessing Static Variables
Static variables can be accessed and updated using the class name. Although Java allows access through an object reference, using the class name is clearer and avoids confusion.
Example: Updating a Shared Variable
class Employee {
static String company = "Tech Solutions";
String employeeName;
Employee(String employeeName) {
this.employeeName = employeeName;
}
public static void main(String[] args) {
Employee e1 = new Employee("Amit");
Employee e2 = new Employee("Neha");
System.out.println(Employee.company);
Employee.company = "Global Technologies";
System.out.println(Employee.company);
}
}
Output
Tech Solutions
Global Technologies
The value changes because both objects share the same static field. If either object later reads Employee.company, it will see the updated value.
Important Note
A static variable is shared, but that does not automatically make operations on it thread-safe. If multiple threads update shared mutable data, synchronization or other concurrency controls may be necessary.
6. Understanding Static Methods
A static method is a method declared with the static keyword. It belongs to the class rather than to an individual object. Static methods can be called directly through the class name and are useful for operations that do not depend on the state of a particular instance.
Syntax
class ClassName {
static void methodName() {
// Method implementation
}
}
Example: A Static Method
class Calculator {
static void displayMessage() {
System.out.println("Welcome to the Calculator");
}
public static void main(String[] args) {
Calculator.displayMessage();
}
}
Output
Welcome to the Calculator
The method is called using Calculator.displayMessage(). An object is not required because the method does not rely on object-specific data.
7. Static Methods with Parameters and Return Values
Static methods can accept parameters and return values just like instance methods. They are particularly useful for calculations and transformations that depend only on the supplied arguments.
Example: Adding Two Numbers
class Calculator {
static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int result = Calculator.add(10, 20);
System.out.println("Sum: " + result);
}
}
Output
Sum: 30
The add() method receives two integer parameters, calculates their sum, and returns the result. It does not need any instance variables, so declaring it static is appropriate.
Example: Finding the Square of a Number
class MathUtility {
static int square(int number) {
return number * number;
}
public static void main(String[] args) {
System.out.println(MathUtility.square(5));
System.out.println(MathUtility.square(8));
}
}
Output
25
64
Utility operations such as these can be called directly without creating utility-class objects.
8. Difference Between Static Variables and Instance Variables
| Feature |
Static Variable |
Instance Variable |
| Association |
Belongs to the class |
Belongs to each object |
| Copies |
One shared field per class definition and class loader |
Each object has its own instance field |
| Declaration |
Uses the static keyword |
Does not use static |
| Access |
Preferred through the class name |
Through an object or instance context |
| Typical purpose |
Shared configuration or common counters |
Object-specific information |
| Example |
static String company; |
String employeeName; |
Example: Comparing Static and Instance Variables
class Employee {
static String company = "ABC Ltd";
String name;
Employee(String name) {
this.name = name;
}
void display() {
System.out.println(name + " works at " + company);
}
public static void main(String[] args) {
Employee e1 = new Employee("Aman");
Employee e2 = new Employee("Riya");
e1.display();
e2.display();
e1.name = "Karan";
e1.display();
e2.display();
}
}
Output
Aman works at ABC Ltd
Riya works at ABC Ltd
Karan works at ABC Ltd
Riya works at ABC Ltd
Changing e1.name affects only the first employee object. The company field remains shared across both objects.
9. Difference Between Static Methods and Instance Methods
| Feature |
Static Method |
Instance Method |
| Association |
Belongs to the class |
Belongs to an object |
| Invocation |
Can be called through the class name |
Normally called through an object |
| Object requirement |
No object is required |
An instance is generally required for an external call |
| Direct access to instance members |
Cannot directly access instance fields or methods without an object reference |
Can access instance members of the current object |
this keyword |
Cannot use this |
Can use this |
| Common purpose |
Utility operations and class-level behavior |
Behavior involving object state |
10. Rules and Restrictions of Static Methods
Static methods have specific restrictions because they do not operate on an automatically available current object.
Rule 1: Static Methods Cannot Directly Access Instance Variables
class Example {
int number = 10;
static void display() {
// System.out.println(number); // Compilation error
}
}
The compiler reports an error because number belongs to an object. A static method can access it through an explicit object reference.
class Example {
int number = 10;
static void display() {
Example obj = new Example();
System.out.println(obj.number);
}
public static void main(String[] args) {
Example.display();
}
}
Rule 2: Static Methods Cannot Use this
class Example {
static void show() {
// System.out.println(this); // Compilation error
}
}
The this keyword represents the current object. Since a static method has no implicit current object, it cannot use this.
Rule 3: Static Methods Can Call Other Static Methods Directly
class Example {
static void first() {
System.out.println("First method");
}
static void second() {
first();
System.out.println("Second method");
}
public static void main(String[] args) {
Example.second();
}
}
Output
First method
Second method
Rule 4: Static Methods Can Call Instance Methods Through an Object
class Example {
void display() {
System.out.println("Instance method called");
}
static void callDisplay() {
Example obj = new Example();
obj.display();
}
public static void main(String[] args) {
Example.callDisplay();
}
}
Output
Instance method called
Rule 5: Static Methods Are Not Overridden Like Instance Methods
Java permits a subclass to declare a static method with the same compatible signature as an accessible static method in its superclass. This is called method hiding, not instance-method overriding. The method selected depends on the class through which the static method is referenced.
class Parent {
static void show() {
System.out.println("Parent static method");
}
}
class Child extends Parent {
static void show() {
System.out.println("Child static method");
}
public static void main(String[] args) {
Parent.show();
Child.show();
}
}
Output
Parent static method
Child static method
11. Static Variables and Static Methods Together
Static variables and methods can work together when a class needs to maintain shared information and provide class-level operations to manage it.
Example: Counting Created Objects
class Counter {
static int count = 0;
Counter() {
count++;
}
static void displayCount() {
System.out.println("Objects created: " + count);
}
public static void main(String[] args) {
new Counter();
new Counter();
new Counter();
Counter.displayCount();
}
}
Output
Objects created: 3
Every time the constructor runs, it increments the shared static variable. The static method then displays the current count without requiring a separate object to invoke it.
12. Understanding the main() Method as Static
In a standard Java application, the Java launcher uses the entry-point method declared as public static void main(String[] args). The method is static so the launcher can invoke it without first creating an instance of the application class.
Meaning of Each Keyword
| Keyword |
Explanation |
public |
Allows the launcher to access the method. |
static |
Allows invocation without an instance of the class. |
void |
Indicates that the method does not return a value. |
main |
The conventional application entry-point method name. |
String[] args |
Receives command-line arguments. |
Example
class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java Programming");
}
}
Output
Welcome to Java Programming
13. Static Initialization Blocks
A static initialization block is a block of code declared using the static keyword. It is useful when static variables require more complex initialization than a simple assignment.
Static initialization blocks execute when the class is initialized, typically before its static members are used for the first time. When a class has multiple static initialization blocks, they execute in their textual order, interleaved with static field initializers.
Example
class Configuration {
static int value;
static {
value = 100;
System.out.println("Static block executed");
}
static void display() {
System.out.println("Value: " + value);
}
public static void main(String[] args) {
Configuration.display();
}
}
Output
Static block executed
Value: 100
The static block initializes the shared field before the static method displays its value.
14. Real-World Applications of Static Variables and Methods
Application 1: Application-Wide Constants
Constants that are shared throughout an application can be declared using static final. This combination is commonly used for values that should not be reassigned after initialization.
class AppConfig {
static final double TAX_RATE = 0.18;
static final int MAX_LOGIN_ATTEMPTS = 3;
public static void main(String[] args) {
System.out.println(TAX_RATE);
System.out.println(MAX_LOGIN_ATTEMPTS);
}
}
Application 2: Utility Methods
Static methods are useful for common calculations that do not depend on object state.
class TemperatureConverter {
static double celsiusToFahrenheit(double celsius) {
return (celsius * 9.0 / 5.0) + 32;
}
public static void main(String[] args) {
System.out.println(
TemperatureConverter.celsiusToFahrenheit(25)
);
}
}
Output
77.0
Application 3: Shared Counters
Static counters can track the number of objects created or the number of operations performed. In multithreaded programs, shared counter updates may require synchronization or atomic classes to avoid race conditions.
Application 4: Factory and Helper Operations
Static methods can provide convenient operations for creating objects, validating input, or converting data when the functionality does not require an existing instance.
15. Advantages of Static Variables and Static Methods
- Memory efficiency: Static fields avoid keeping a separate copy of shared data in every object.
- Convenient access: Static methods can be invoked using the class name.
- Code reuse: Utility methods can be shared across different parts of an application.
- Centralized information: Shared configuration and common values can be maintained in one place.
- Simple design: Operations that do not depend on object state can be organized clearly.
- Useful constants: The
static final combination supports class-level constants.
16. Disadvantages and Limitations
- Shared mutable state: Changes to a static variable can affect every part of the application that uses it.
- Testing difficulties: Mutable static state may persist between tests and cause tests to interfere with each other.
- Limited polymorphism: Static methods do not participate in runtime overriding in the same way as instance methods.
- Concurrency risks: Unsynchronized updates to shared mutable static fields can cause race conditions.
- Design coupling: Excessive use of static members can make code harder to maintain, extend, and test.
- Lifecycle considerations: Static fields remain associated with their class while the class remains loaded.
17. Common Mistakes to Avoid
| Mistake |
Why It Is Incorrect |
Correct Approach |
| Accessing an instance variable directly from a static method |
No implicit object is available. |
Use an object reference or make the field static only if it truly represents shared state. |
Using this in a static method |
this refers to the current object. |
Use an instance method when current-object access is required. |
| Creating an object for every static method call |
Unnecessary when the operation is class-level. |
Call the method through the class name. |
| Making every field static |
Different objects may need different values. |
Use instance fields for object-specific information. |
| Assuming static fields are automatically thread-safe |
Shared access can lead to race conditions. |
Use appropriate synchronization or concurrency utilities. |
| Confusing method hiding with overriding |
Static methods are resolved differently from instance methods. |
Use instance methods when runtime polymorphism is needed. |
18. Best Practices
- Use static variables only for data that should genuinely be shared at the class level.
- Use
static final for suitable constants.
- Prefer class-name access, such as
ClassName.variableName and ClassName.methodName().
- Use static methods for stateless utility operations.
- Keep object-specific information in instance variables.
- Avoid unnecessary mutable global state.
- Consider thread safety when shared fields can be accessed by multiple threads.
- Document the purpose of important shared variables so their behavior remains understandable.
19. Practice Exercises
Exercise 1: Student College Information
Create a Student class with instance variables for student name and roll number, plus a static variable for the college name. Create three student objects and display their information.
Exercise 2: Object Counter
Create a class with a static counter. Increment it inside the constructor and write a static method that displays how many objects have been created.
Exercise 3: Calculator Utility
Create a Calculator class with static methods for addition, subtraction, multiplication, and division. Call each method through the class name.
Exercise 4: Employee Company Details
Create an Employee class with an instance variable for the employee name and a static variable for the company name. Change the company name and observe the effect on different objects.
Exercise 5: Static Method Restrictions
Write a program containing a static method and an instance method. Try accessing an instance variable directly from the static method, observe the compilation error, and correct it using an object reference.
20. Mini Project: Employee Management Counter
Objective: Create a small employee management example that demonstrates static variables, instance variables, constructors, and static methods.
Requirements
- Each employee should have a unique employee ID and an employee name.
- A static variable should store the total number of employees created.
- A static variable should store the shared company name.
- A static method should display the employee count.
- An instance method should display individual employee details.
Sample Implementation
class Employee {
private int employeeId;
private String name;
static String companyName = "JustAcademy Technologies";
static int employeeCount = 0;
Employee(int employeeId, String name) {
this.employeeId = employeeId;
this.name = name;
employeeCount++;
}
void displayDetails() {
System.out.println("Employee ID: " + employeeId);
System.out.println("Name: " + name);
System.out.println("Company: " + companyName);
}
static void displayEmployeeCount() {
System.out.println("Total Employees: " + employeeCount);
}
public static void main(String[] args) {
Employee e1 = new Employee(101, "Aman");
Employee e2 = new Employee(102, "Priya");
e1.displayDetails();
e2.displayDetails();
Employee.displayEmployeeCount();
}
}
Expected Output
Employee ID: 101
Name: Aman
Company: JustAcademy Technologies
Employee ID: 102
Name: Priya
Company: JustAcademy Technologies
Total Employees: 2
This project demonstrates how static variables maintain shared information while instance variables maintain employee-specific details.
21. Interview Questions and Answers
Q1. What is a static variable in Java?
A static variable is a class-level field shared by instances of the declaring class. It is declared using the static keyword.
Q2. What is a static method?
A static method belongs to the class and can be called using the class name without creating an object.
Q3. What is the difference between static and instance variables?
A static variable is shared by the class's instances, whereas each object has its own instance variable.
Q4. Can a static method access an instance variable directly?
No. It needs an explicit object reference to access an instance variable.
Q5. Can a static method call another static method?
Yes. A static method can call another accessible static method directly within the same class or through the appropriate class name.
Q6. Can a static method use the this keyword?
No. The this keyword represents the current object, which is not implicitly available in a static method.
Q7. Why is the main() method static?
In a standard Java application, the launcher can invoke the entry-point method without creating an instance of the application class.
Q8. Can static variables be modified?
Yes, unless restricted by declarations such as final. Changes to a mutable static field are visible to code accessing that same field.
Q9. What is a static initialization block?
It is a block of code used to initialize static state when the class is initialized.
Q10. Can static methods be overridden?
Static methods are hidden rather than overridden through runtime instance-method polymorphism.
Q11. Are static variables thread-safe?
No. A static variable is shared, but sharing alone does not ensure that concurrent reads and writes are thread-safe.
Q12. When should you use a static method?
Use a static method when its operation does not require the state of a particular object, such as a calculation or general utility operation.
22. Quick Revision Checklist
static associates a member with the class rather than a particular object.
- Static variables are shared by instances of the declaring class.
- Instance variables store object-specific data.
- Static methods can be called through the class name.
- Static methods cannot directly access instance members without an object reference.
- The
this keyword cannot be used in a static method.
- Static methods can call other static methods directly.
- Static fields receive default values if they are not explicitly initialized.
static final is commonly used for class-level constants.
- Static methods use method hiding rather than instance-method overriding.
- Shared mutable static state may require concurrency controls.
- Use static members only when class-level behavior or shared state is appropriate.
23. Conclusion
Static variables and static methods are fundamental concepts in Java that help developers manage shared data and class-level operations. Static variables are useful for common information such as application configuration, shared counters, and constants. Static methods are useful for utility functions and operations that do not depend on a specific object's state.
Understanding the differences between static and instance members helps you design cleaner, more maintainable Java applications. Practice the examples and exercises in these notes to strengthen your understanding of the static keyword and prepare for Java programming interviews.
Learn More with JustAcademy
Explore the Core Java Training Course to continue learning Java fundamentals, object-oriented programming, classes, methods, inheritance, exception handling, collections, and other essential concepts.
Interested in learning more? Register for a Course Demo or visit the JustAcademy website for additional learning resources.